import type { VbenFormSchema } from '#/adapter/form'

import type { Ref } from 'vue'
import { computed, nextTick, watch } from 'vue'

import { LocaleDictionaryPrefix } from '#/config'
import { formValidFormat } from '#/utils/formValidator'
import type { ExtendedFormApi } from '@vben/common-ui'
import { $t } from '@vben/locales'
import { isEmpty } from '@vben/utils'

export function getAddEditFormSchema(opts?: {
    formApi?: ExtendedFormApi
    rowId: Ref<null | number>
}) {
    const { rowId, formApi } = opts || {}
    const isEdit = computed(() => !isEmpty(rowId?.value))
    // 不能编辑code 否则导致前端ui显示错误
    watch(
        isEdit,
        (val) => {
            if (opts?.formApi) {
                nextTick(() => {
                    formApi?.updateSchema([
                        {
                            fieldName: 'code',
                            componentProps: {
                                disabled: val
                            }
                        }
                    ])
                })
            }
        },
        {
            immediate: true
        }
    )
    return [
        {
            fieldName: 'name',
            label: $t('page.system.children.dictionary.children.form.name'),
            defaultValue: '',
            component: 'Input'
        },
        {
            fieldName: 'code',
            label: $t('page.system.children.dictionary.children.form.code'),
            component: 'Input',
            defaultValue: '',
            help: $t('ui.formRules.startWith', ['', LocaleDictionaryPrefix]),
            componentProps: {
                placeholder: $t('ui.formRules.startWith', ['', LocaleDictionaryPrefix])
            },
            rules: formValidFormat(
                (str: string) => {
                    if (LocaleDictionaryPrefix) {
                        return str.startsWith(LocaleDictionaryPrefix)
                    }
                    return true
                },
                {
                    message: $t('ui.formRules.startWith', ['', LocaleDictionaryPrefix])
                }
            )
        },

        {
            fieldName: 'note',
            label: $t('common.remark'),
            component: 'Input',
            defaultValue: ''
        }
    ] as VbenFormSchema[]
}
